using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AssetFrame.Message;
using System.Reflection;
using SysFrame.BP;
using SysFrame.Message;
using System.Data;
using Newtonsoft.Json.Linq;

namespace AssetFrame.BP
{
    /// <summary>
    /// asset_a1方法
    /// </summary>
    public class BLLasset_a1
    {
        public Iasset_a1 interface_asset_a1;

        public BLLasset_a1()
        {
            object obj = BPBase.GetAchieve("AssetFrame.BP", "asset_a1");
            interface_asset_a1 = (Iasset_a1)obj;
        }


        /// <summary>
        /// 得到asset_a1实体
        /// </summary>
        /// <param name="msq">条件</param>
        /// <returns></returns>
        public List<Msasset_a1> Getasset_a1MsByQuery(MsQuery msq)
        {
            return interface_asset_a1.Getasset_a1MsByQuery(msq);
        }

        /// <summary>
        /// 通过ASSET_A1_AUTOID得到实体
        /// </summary>
        /// <param name="ASSET_A1_AUTOID">ID</param>
        /// <returns>实体</returns>
        public Msasset_a1 Getasset_a1MsByKey(string ASSET_A1_AUTOID)
        {
            MsQuery msquery = new MsQuery();
            msquery.strquery += " and ASSET_A1_AUTOID='" + ASSET_A1_AUTOID + "' ";
            List<Msasset_a1> lstData = Getasset_a1MsByQuery(msquery);
            return lstData[0];
        }

        /// <summary>
        ///  保存asset_a1信息
        /// </summary>
        /// <param name="ms">实体信息</param>
        /// <returns>消息</returns>
        public MsReturned Saveasset_a1(Msasset_a1 ms)
        {
            //如果是更新 判断是否需要记录更新日志
            if (ms.ASSET_A1_AUTOID != null && ms.ASSET_A1_AUTOID.ToString() != "" && ms.ASSET_A1_AUTOID.ToString() != "0")
            {
                if (new BLLsystem_4().Getsystem_4ByCode("006001").System_4_50 == "1")
                {
                    Msasset_a1 oldms = Getasset_a1MsByKey(ms.ASSET_A1_AUTOID.ToString());
                    PropertyInfo[] propertys = new Msasset_a1().GetType().GetProperties();
                    //循环属性对比 
                    for (int i = 0; i < propertys.Length; i++)
                    {
                        if (propertys[i].Name.IndexOf("ASSET_A1_") >= 0 && propertys[i].GetValue(oldms, null) != propertys[i].GetValue(ms, null) && propertys[i].GetValue(ms, null) != null)
                        {
                            //时间必定改变
                            if (propertys[i].Name == "ASSET_A1_MAKETIME")
                            {
                                continue;
                            }
                            //说明改变了
                            Mssys_asset_a3 sysa3 = new Mssys_asset_a3();
                            sysa3.SYS_ASSET_A3_10 = ms.ASSET_A1_AUTOID;
                            sysa3.SYS_ASSET_A3_20 = propertys[i].Name;
                            sysa3.SYS_ASSET_A3_30 = propertys[i].GetValue(oldms, null) == null ? "" : propertys[i].GetValue(oldms, null).ToString();
                            sysa3.SYS_ASSET_A3_40 = propertys[i].GetValue(ms, null).ToString();
                            sysa3.SYS_ASSET_A3_50 = ms.typecode1;//动作分类， 来自编辑 批量编辑 接口编辑 还是业务
                            sysa3.SYS_ASSET_A3_60 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            sysa3.SYS_ASSET_A3_70 = ms.typecode2;//动作来源相关ID
                            if (sysa3.SYS_ASSET_A3_30 != sysa3.SYS_ASSET_A3_40)
                            {
                                new BLLsys_asset_a3().Savesys_asset_a3(sysa3);
                            }
                        }
                    }
                }
            }
            return interface_asset_a1.Saveasset_a1(ms);
        }


        /// <summary>
        /// 日期加流水号 临时方法
        /// </summary>
        /// <returns></returns>
        public static string GetMaxSysCode()
        {
            MsQuery msq = new MsQuery();
            string date = DateTime.Now.ToString("yyyyMMdd");
            msq.strquery += " and ASSET_A1_30 like '" + date + "%'";
            DataTable dt = new BLLasset_a1().Getasset_a1DataByQuery(msq);
            return date + (dt.Rows.Count + 1).ToString().PadLeft(4, '0');
        }

        /// <summary>
        /// 得到数据类型
        /// </summary>
        /// <param name="msquery">条件</param>
        /// <returns>数据类型</returns>
        public MsReturned Getasset_a1ByQuery(MsQuery msquery)
        {
            return interface_asset_a1.Getasset_a1ByQuery(msquery);
        }

        /// <summary>
        /// 得到数据类型
        /// </summary>
        /// <param name="msquery">条件</param>
        /// <returns>数据类型</returns>
        public DataTable Getasset_a1DataByQuery(MsQuery msquery)
        {
            return interface_asset_a1.Getasset_a1DataByQuery(msquery);
        }

        public DataTable Getasset_a1GroupDataByQuery(MsQuery msquery, List<string> group)
        {
            return interface_asset_a1.Getasset_a1GroupDataByQuery(msquery, group);
        }

        /// <summary>
        /// 删除asset_a1
        /// </summary>
        /// <param name="msq">条件</param>
        /// <returns></returns>
        public MsReturned Deleteasset_a1ByQuery(MsQuery msq)
        {
            return interface_asset_a1.Deleteasset_a1ByQuery(msq);
        }
        /// <summary>
        /// 删除asset_a1
        /// </summary>
        /// <param name="msq">条件</param>
        /// <returns></returns>
        public MsReturned Deleteasset_a1ByKey(string ASSET_A1_AUTOID)
        {
            MsQuery msquery = new MsQuery();

            if (ASSET_A1_AUTOID.IndexOf(",") > 0)
            {
                msquery.strquery += " and ASSET_A1_AUTOID in (" + ASSET_A1_AUTOID + ") ";
            }
            else
            {
                msquery.strquery += " and ASSET_A1_AUTOID='" + ASSET_A1_AUTOID + "' ";
            }
            return interface_asset_a1.Deleteasset_a1ByQuery(msquery);
        }

        /// <summary>
        /// 验证数据
        /// </summary>
        /// <param name="excelData">数据集合</param>
        /// <param name="batch">批次</param>
        /// <returns></returns>
        public List<MsReturned> CheckData(JArray excelData, string batch)
        {
            List<MsReturned> listres = new List<MsReturned>();
            /**
             * 1. 拿到所有字段配置 和 字典 准备缓存数据
             * 2. 根据批号生成临时表【暂无】
             * 3. 开始遍历
             *  4.必填 不为空,判断是否存在[必须要有 A1_30 ，必填 notnull] 012001
             *  5.数据类型 [Int ，DateTime] 012002 012003
             *  6.字典存在 关联表  012004
             *      7.自动添加【暂无】
             *  8.能不能插入到库【暂无】
             *  9.根据错误字典生成说明
             */

            //1. 拿到所有字段配置 和 字典 准备缓存数据

            //字段配置
            List<Mssys_asset_a1> listsysA1 = new BLLsys_asset_a1().Getsys_asset_a1MsByQuery(new MsQuery());
            Dictionary<string, Mssys_asset_a1> dicsysA1 = new Dictionary<string, Mssys_asset_a1>();
            foreach (var item in listsysA1)
            {
                if (item.SYS_ASSET_A1_160 != null && !string.IsNullOrEmpty(item.SYS_ASSET_A1_160.ToString()))
                {
                    dicsysA1.Add(item.SYS_ASSET_A1_160, item);
                    dicsysA1.Add("str" + item.SYS_ASSET_A1_160, item);
                }
            }
            //错误字典
            List<Mssystem_4> listsys4 = new BLLsystem_4().Getsystem_4ByTypeCode("012");
            Dictionary<string, Mssystem_4> dicsys4 = new Dictionary<string, Mssystem_4>();
            foreach (var item in listsys4)
            {
                dicsys4.Add(item.System_4_20, item);
            }
            //资产编号集合
            List<string> listA1Code = Getasset_a1MsByQuery(new MsQuery()).ConvertAll(a1 => a1.ASSET_A1_30);
            //必须有
            List<string> listmust = (new string[] { "ASSET_A1_30" }).ToList();
            //不为空
            List<string> listnotnull = (new string[] { "strASSET_A1_60", "ASSET_A1_10" }).ToList();
            //Int
            List<string> listInt = listsysA1.FindAll(sysa1 => sysa1.SYS_ASSET_A1_170 == "Int").ConvertAll(sysa1 => sysa1.SYS_ASSET_A1_160);
            //Date
            List<string> listDate = listsysA1.FindAll(sysa1 => sysa1.SYS_ASSET_A1_170 == "Date").ConvertAll(sysa1 => sysa1.SYS_ASSET_A1_160);
            //Join
            List<string> listJoin = listsysA1.FindAll(sysa1 => !string.IsNullOrEmpty(sysa1.SYS_ASSET_A1_60) 
            && !string.IsNullOrEmpty(sysa1.SYS_ASSET_A1_70) && !string.IsNullOrEmpty(sysa1.SYS_ASSET_A1_80)).ConvertAll(sysa1 => "str" + sysa1.SYS_ASSET_A1_160);
            //关联表缓存 表名 表
            Dictionary<string, DataTable> dicJoin = new Dictionary<string, DataTable>();

            //3. 开始遍历
            foreach (JObject item in excelData)
            {
                IDictionary<string,JToken> dicitem = (IDictionary<string, JToken>)item;
                MsReturned msr = new MsReturned();
                //关联表的值
                JObject joinVal = new JObject();
                //错误消息
                List<string> listerrtext = new List<string>();

                #region  4.必填 不为空,判断是否存在[必须要有 A1_30 ，必填 notnull] 012001

                /**
                 * 1.A1_30没有直接返回
                 * 2.编号是否在库里  strMsId MsRbool
                 * 3.是否有值 notnull 新增再判断 012001
                 */
                //1.A1_30没有直接返回
                bool bmust = false;
                foreach (var must in listmust)
                {
                    if (!dicitem.Keys.Contains(must) || string.IsNullOrEmpty(dicitem[must].ToString())) {
                        bmust = true;
                        break;
                    }
                }
                if (bmust) {
                    continue;
                }

                msr.strMsId = dicitem["ASSET_A1_30"].ToString();
                //2.编号是否在库里 存在是true
                msr.MsRbool = listA1Code.Contains(dicitem["ASSET_A1_30"].ToString());

                //3.是否有值 notnull 新增再判断
                if (!msr.MsRbool)
                {
                    foreach (var notnull in listnotnull)
                    {
                        try
                        {
                            if (dicitem[notnull] == null || string.IsNullOrEmpty(dicitem[notnull].ToString()))
                            {
                                //${field} ${value}
                                //string errtext = listsys4.Find(sys4 => sys4.System_4_20 == "012001").System_4_50;
                                //errtext = errtext.Replace("${field}", listsysA1.Find(sysa1 => sysa1.SYS_ASSET_A1_160 == notnull).SYS_ASSET_A1_50);
                                string errtext = dicsys4["012001"].System_4_50; 
                                errtext = errtext.Replace("${field}", dicsysA1[notnull].SYS_ASSET_A1_50); 
                                listerrtext.Add(errtext);
                            }
                        }
                        catch(Exception e) { }
                    }
                }

                #endregion

                //key
                foreach (var key in dicitem.Keys)
                {
                    //值
                    var value = dicitem[key].ToString();

                    #region 5.数据类型 [Int ，DateTime] 012002 012003

                    //Int
                    if (listInt.Contains(key)) {
                        try {
                            Convert.ToInt32(value);
                        }
                        catch{
                            //${field} ${value}
                            //string errtext = listsys4.Find(sys4 => sys4.System_4_20 == "012002").System_4_50;
                            //errtext = errtext.Replace("${field}", listsysA1.Find(sysa1 => sysa1.SYS_ASSET_A1_160 == key).SYS_ASSET_A1_50).
                            //    Replace("${value}", value);

                            string errtext = dicsys4["012002"].System_4_50;
                            errtext = errtext.Replace("${field}", dicsysA1[key].SYS_ASSET_A1_50).Replace("${value}", value);
                            listerrtext.Add(errtext);
                        }
                    }
                    //Date
                    if (listDate.Contains(key))
                    {
                        try
                        {
                            Convert.ToDateTime(value);
                        }
                        catch
                        {
                            //${field} ${value}
                            //string errtext = listsys4.Find(sys4 => sys4.System_4_20 == "012003").System_4_50;
                            //errtext = errtext.Replace("${field}", listsysA1.Find(sysa1 => sysa1.SYS_ASSET_A1_160 == key).SYS_ASSET_A1_50).
                            //    Replace("${value}", value);

                            string errtext = dicsys4["012003"].System_4_50;
                            errtext = errtext.Replace("${field}", dicsysA1[key].SYS_ASSET_A1_50).Replace("${value}", value);
                            listerrtext.Add(errtext);
                        }
                    }
                    #endregion

                    #region 6.字典存在 关联表  012004
                    /**
                     * 1.找到关联表
                     * 2.找到表  如果存在就取出来
                     * 3.如果没有 就拿到 放 dicJoin 里
                     * 4.如果找到 赋值
                     */

                    if (listJoin.Contains(key))
                    {
                        //关联表配置
                        //Mssys_asset_a1 sysA1 = listsysA1.Find(sysa1 => "str"+sysa1.SYS_ASSET_A1_160 == key);
                        Mssys_asset_a1 sysA1 = dicsysA1[key];
                        //关联表数据
                        DataTable joindt = new DataTable();
                        try
                        {
                            //2.找到表  如果存在就取出来
                            if (dicJoin.Keys.Contains(sysA1.SYS_ASSET_A1_60))
                            {
                                joindt = dicJoin[sysA1.SYS_ASSET_A1_60];
                            }
                            //3.如果没有 就拿到 放 dicJoin 里
                            else
                            {
                                joindt = BLLsys_asset_a1.GetIDJoinTable(sysA1);
                                dicJoin[sysA1.SYS_ASSET_A1_60] = joindt;
                            }
                            DataRow[] rows = joindt.Select(" convert(" + sysA1.SYS_ASSET_A1_70 + ",'System.String') = '" + value + "'");
                            //如果没找到
                            if (rows.Length == 0 || string.IsNullOrEmpty(rows[0][0].ToString()))
                            {
                                //${field} ${value}
                                //string errtext = listsys4.Find(sys4 => sys4.System_4_20 == "012004").System_4_50;

                                string errtext = dicsys4["012004"].System_4_50;
                                errtext = errtext.Replace("${field}", sysA1.SYS_ASSET_A1_50).
                                    Replace("${value}", value);
                                listerrtext.Add(errtext);
                            }
                            //4.如果找到 赋值
                            else
                            {
                                joinVal.Add(sysA1.SYS_ASSET_A1_160, rows[0][0].ToString());
                            }
                        }
                        catch (Exception e)
                        {
                            
                        }

                    }
                    #endregion

                }
                //消息
                msr.strMS = string.Join(";", listerrtext);
                //扩展
                msr.obj1 = joinVal;

                listres.Add(msr);
            }


            return listres;
        }
    }
}
